package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.entity.Admin;
import com.southwind.exception.ShopException;
import com.southwind.form.AdminForm;
import com.southwind.result.ResponseEnum;
import com.southwind.service.AdminService;
import com.southwind.util.JwtUtil;
import com.southwind.util.ResultVOUtil;
import com.southwind.vo.AdminVO;
import com.southwind.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author southwind
 * @since 2025-02-19
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public ResultVO login(AdminForm adminForm){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminForm.getUsername());
        Admin admin = this.adminService.getOne(queryWrapper);
        if(admin == null) throw new ShopException(ResponseEnum.ADMIN_USERNAME_ERROR.getMsg());
        if(!admin.getPassword().equals(adminForm.getPassword()))
            throw new ShopException(ResponseEnum.ADMIN_PASSWORD_ERROR.getMsg());
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);
        adminVO.setToken(JwtUtil.createToken(admin.getAdminId(), admin.getUsername()));
        return ResultVOUtil.success(adminVO);
    }

    @GetMapping("/checkToken/{token}")
    public ResultVO checkToken(@PathVariable("token") String token){
        boolean checkToken = JwtUtil.checkToken(token);
        if(checkToken) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(ResponseEnum.TOKEN_ERROR.getMsg());
    }

}

